import pandas as pd
import quandl
import math
import datetime
import numpy as np
from sklearn import preprocessing, cross_validation, svm
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from matplotlib import style
import pickle


style.use('ggplot')
# df = quandl.get("ZFB/NKE_TOT_CURR_LIAB_Q", authtoken="5sNmi8Zr61MU77qa-4xY")
df = quandl.get("WIKI/GOOGL")
df = df[['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close','Adj. Volume']]
df['HL_PCT'] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Close'] * 100.0
df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100.0

#         price
df = df[['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume']]

forcast_col = 'Adj. Close'
df.fillna(-99999, inplace=True)

forcast_out = int(math.ceil(0.1*len(df)))
# print(df.head())
df['label'] = df[forcast_col].shift(-forcast_out)
# print(df.head())

x = np.array(df.drop(['label'], 1))
# print(x, len(x))
x = preprocessing.scale(x, 0)
# print(x, len(x))
x_lately = x[-forcast_out:]
x = x[:-forcast_out]
# print(x)
df.dropna(inplace=True)
y = np.array(df['label'])
# y = np.array(df['label'])
# print(len(x), len(y), len(x_lately))
x_train, x_test, y_train, y_test = cross_validation.train_test_split(x, y, test_size=0.2)
clf = LinearRegression(n_jobs=-1)
# clf = svm.SVR(kernel='poly')
clf.fit(x_train, y_train)

with open('linearregression.pickl', 'wb') as f:
    pickle.dump(clf, f)

pickle_in = open('linearregression.pickl', 'rb')
clf = pickle.load(pickle_in)
confidence = clf.score(x_test, y_test)

forcast_set = clf.predict(x_lately)
# print(confidence, forcast_set, forcast_out)

df['Forecast'] = np.nan

last_date = df.iloc[-1].name

last_unix = last_date.timestamp()
# print(last_date)
# print(last_unix)
# print(len(df.columns))
one_day = 86400  # 3600s * 24h
next_unix = last_unix + one_day

for i in forcast_set:
    next_date = datetime.datetime.fromtimestamp(next_unix)
    next_unix += one_day
    df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)] + [i]
print(df.head())
print(df.tail())
df[forcast_col].plot()
df['Forecast'].plot()
plt.legend(loc=4)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()
